<template>
  <div class="my-demands-container">
    <!-- 顶部搜索工具栏 -->
    <!-- <div class="search-toolbar">
      <div>
        <el-input
          v-model="keyword"
          placeholder="请输入需求名称/资源名称/数源单位等关键字"
          clearable
          @keyup.enter="fetchData"
        >
          <template #append>
            <div class="search-button" @click="fetchData">
              <img src="@/assets/imgs/home/search.png" />
              <span>搜索</span>
            </div>
          </template>
        </el-input>
      </div>
    </div> -->

    <!-- 结果统计 -->
    <div class="result-sort-container">
      <div class="result-count">
        共有<span class="result-count-number">
          {{ total }}
        </span>
        个结果
      </div>
      <el-button @click="handleOpenDemand"> 提交需求 </el-button>
    </div>

    <!-- 需求卡片列表 -->
    <div class="demand-cards-container" v-loading="loading">
      <template v-if="tableData.length > 0">
        <div v-for="item in tableData" :key="item.id" class="demand-card-item">
          <!-- 标题行 -->
          <div class="card-header">
            <div class="card-header-content">
              <span class="card-title">{{ item.applicationTitle }}</span>
            </div>

            <div class="card-actions" @click="handleView(item)">
              <el-button link type="primary">查看</el-button>
            </div>
          </div>

          <!-- 标签 -->
          <div class="card-tags">
            <el-tag
              size="small"
              :type="getStatusType(item.status)"
              style="background-color: #f0f9eb"
            >
              {{ getStatusLabel(item.status) }}
            </el-tag>
          </div>

          <!-- 摘要信息 -->
          <div class="card-summary">
            <div class="summary-item">
              <span class="summary-label">联系电话：</span>
              <span class="summary-value">{{ item.contactPhone }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">联系地址：</span>
              <span class="summary-value">{{ item.contactAddress }}</span>
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="card-footer">
            <div class="info-item">
              <img src="@/assets/imgs/data/time.png" />
              <span>申请时间：{{ item.createTime }}</span>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="!loading">
        <el-empty description="暂无需求数据" />
      </template>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 40, 80]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="getMyDemands"
        @size-change="getMyDemands"
      />
    </div>

    <el-dialog
      v-model="showSubmitDialog"
      title="提交需求申请"
      width="800px"
      :before-close="handleCloseDialog"
    >
      <el-form :model="demandForm" :rules="demandRules" ref="demandFormRef" label-width="120px">
        <el-form-item label="申请标题" prop="applicationTitle">
          <el-input v-model="demandForm.applicationTitle" placeholder="请输入申请标题" />
        </el-form-item>

        <el-form-item label="申请原因" prop="applicationReason">
          <el-input
            v-model="demandForm.applicationReason"
            type="textarea"
            :rows="3"
            placeholder="请输入申请原因"
          />
        </el-form-item>

        <el-form-item label="应用场景" prop="applicationScenario">
          <el-input
            v-model="demandForm.applicationScenario"
            type="textarea"
            :rows="2"
            placeholder="请输入数据的应用场景描述"
          />
        </el-form-item>

        <el-form-item label="使用时间" prop="useTime">
          <el-date-picker
            v-model="demandForm.useTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="demandForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="联系地址" prop="contactAddress">
          <el-input v-model="demandForm.contactAddress" placeholder="请输入联系地址" />
        </el-form-item>

        <el-form-item label="服务范围" prop="serviceScope">
          <el-input
            v-model="demandForm.serviceScope"
            type="textarea"
            :rows="2"
            placeholder="基于开发数据开发的应用上线之后的用户群体以及对应的服务范围"
          />
        </el-form-item>

        <el-form-item label="预期成效" prop="expectedEffect">
          <el-input
            v-model="demandForm.expectedEffect"
            type="textarea"
            :rows="3"
            placeholder="基于开放数据开发的应用上线之后的社会效益、经济效益"
          />
        </el-form-item>

        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="demandForm.systemName" placeholder="使用开放数据的业务系统名称" />
        </el-form-item>

        <el-form-item label="部署地点" prop="deploymentLocation">
          <el-input
            v-model="demandForm.deploymentLocation"
            placeholder="使用开放数据的业务系统部署地点/机房地址"
          />
        </el-form-item>

        <el-form-item label="系统IP" prop="systemIp">
          <el-input v-model="demandForm.systemIp" placeholder="使用开放数据的业务系统IP" />
        </el-form-item>

        <el-form-item label="系统URL" prop="systemUrl">
          <el-input v-model="demandForm.systemUrl" placeholder="使用开放数据的业务系统URL地址" />
        </el-form-item>

        <el-form-item label="等保备案号" prop="levelProtectionCode">
          <el-input
            v-model="demandForm.levelProtectionCode"
            placeholder="使用开放数据的业务系统等级保护备案编号"
          />
        </el-form-item>

        <el-form-item label="等保级别" prop="levelProtectionLevel">
          <el-select v-model="demandForm.levelProtectionLevel" placeholder="请选择等保级别">
            <el-option
              v-for="item in levelProtectionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSubmitDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitDemand">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog
      v-model="showViewDialog"
      title="需求详情"
      width="800px"
      :before-close="handleCloseViewDialog"
    >
      <el-form :model="viewForm" ref="viewFormRef" label-width="120px" :disabled="true">
        <el-form-item label="申请标题">
          <el-input v-model="viewForm.applicationTitle" />
        </el-form-item>

        <el-form-item label="申请原因">
          <el-input v-model="viewForm.applicationReason" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="应用场景">
          <el-input v-model="viewForm.applicationScenario" type="textarea" :rows="2" />
        </el-form-item>

        <el-form-item label="使用时间">
          <el-date-picker
            v-model="viewForm.useTime"
            type="daterange"
            range-separator="至"
            value-format="YYYY-MM-DD"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="viewForm.contactPhone" />
        </el-form-item>

        <el-form-item label="联系地址">
          <el-input v-model="viewForm.contactAddress" />
        </el-form-item>

        <el-form-item label="服务范围">
          <el-input v-model="viewForm.serviceScope" type="textarea" :rows="2" />
        </el-form-item>

        <el-form-item label="预期成效">
          <el-input v-model="viewForm.expectedEffect" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="系统名称">
          <el-input v-model="viewForm.systemName" />
        </el-form-item>

        <el-form-item label="部署地点">
          <el-input v-model="viewForm.deploymentLocation" />
        </el-form-item>

        <el-form-item label="系统IP">
          <el-input v-model="viewForm.systemIp" />
        </el-form-item>

        <el-form-item label="系统URL">
          <el-input v-model="viewForm.systemUrl" />
        </el-form-item>

        <el-form-item label="等保备案号">
          <el-input v-model="viewForm.levelProtectionCode" />
        </el-form-item>

        <el-form-item label="等保级别">
          <el-select v-model="viewForm.levelProtectionLevel" :disabled="true">
            <el-option
              v-for="item in levelProtectionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-tag :type="getStatusType(viewForm.status)">
            {{ getStatusLabel(viewForm.status) }}
          </el-tag>
        </el-form-item>

        <!-- 回复内容 -->
        <el-form-item label="受理意见" v-if="viewForm.replyContent">
          <el-input v-model="viewForm.replyContent" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="受理时间" v-if="viewForm.replyTime">
          <el-input v-model="viewForm.replyTime" :disabled="true" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showViewDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { FormInstance, FormRules } from 'element-plus'
import * as portalApi from '@/api/portal'

interface DemandData {
  id: number
  applicationTitle: string
  applicationReason: string
  applicationScenario: string
  useTimeStart: string
  useTimeEnd: string
  contactPhone: string
  contactAddress: string
  serviceScope: string
  expectedEffect: string
  systemName: string
  deploymentLocation: string
  systemIp: string
  systemUrl: string
  levelProtectionCode: string
  levelProtectionLevel: string
  replyContent: string
  replyTime: string
  status: string
  createTime: string
  createId: string
  replyId: string
}

interface DictOption {
  label: string
  value: string
}

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const levelProtectionOptions = ref<DictOption[]>([])
const demandStatusOptions = ref<DictOption[]>([])

const tableData = ref<DemandData[]>([])

// 弹窗控制
const showSubmitDialog = ref(false)
const showViewDialog = ref(false)
const demandFormRef = ref<FormInstance>()

// 表单数据
const demandForm = reactive({
  applicationTitle: '',
  applicationReason: '',
  applicationScenario: '',
  useTime: [],
  contactPhone: '',
  contactAddress: '',
  serviceScope: '',
  expectedEffect: '',
  systemName: '',
  deploymentLocation: '',
  systemIp: '',
  systemUrl: '',
  levelProtectionCode: '',
  levelProtectionLevel: ''
})

// 查看表单数据
const viewForm = reactive({
  id: 0,
  applicationTitle: '',
  applicationReason: '',
  applicationScenario: '',
  useTime: [],
  contactPhone: '',
  contactAddress: '',
  serviceScope: '',
  expectedEffect: '',
  systemName: '',
  deploymentLocation: '',
  systemIp: '',
  systemUrl: '',
  levelProtectionCode: '',
  levelProtectionLevel: '',
  replyContent: '',
  replyTime: '',
  status: '',
  createTime: '',
  createId: '',
  replyId: ''
})

// 表单验证规则
const demandRules: FormRules = {
  applicationTitle: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
  applicationReason: [{ required: true, message: '请输入申请原因', trigger: 'blur' }],
  applicationScenario: [{ required: true, message: '请输入数据的应用场景', trigger: 'blur' }],
  useTime: [{ required: true, message: '请选择使用时间', trigger: 'change' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactAddress: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  serviceScope: [
    {
      required: true,
      message: '基于开发数据开发的应用上线之后的用户群体以及对应的服务范围',
      trigger: 'blur'
    }
  ],
  expectedEffect: [
    {
      required: true,
      message: '基于开放数据开发的应用上线之后的社会效益、经济效益',
      trigger: 'blur'
    }
  ]
  // systemName: [{ required: true, message: '使用开放数据的业务系统名称', trigger: 'blur' }],
  // deploymentLocation: [{ required: true, message: '使用开放数据的业务系统部署地点/机房地址', trigger: 'blur' }],
  // systemIp: [
  //   { required: true, message: '使用开放数据的业务系统IP', trigger: 'blur' },
  //   {
  //     pattern: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  //     message: '请输入正确的IP地址',
  //     trigger: 'blur'
  //   }
  // ],
  // systemUrl: [
  //   { required: true, message: '使用开放数据的业务系统URL地址', trigger: 'blur' },
  //   { pattern: /^https?:\/\/.+\..+$/, message: '请输入正确的URL地址', trigger: 'blur' }
  // ],
  // levelProtectionCode: [{ required: true, message: '使用开放数据的业务系统等级保护备案编号', trigger: 'blur' }],
  // levelProtectionLevel: [{ required: true, message: '请选择等保级别', trigger: 'change' }]
}

// 获取等保级别字典数据
const getLevelProtectionOptions = async () => {
  try {
    const res = await portalApi.getDictByCode({ dictType: 'protectionLevel' })
    if (res) {
      // 假设返回的数据格式为 { data: [{ label: '一级', value: '一级' }, ...] }
      levelProtectionOptions.value = res || []
    } else {
      console.warn('获取等保级别字典数据失败，使用默认选项')
    }
  } catch (error) {
    console.error('获取等保级别字典数据失败:', error)
    // 失败时使用默认选项
    levelProtectionOptions.value = [
      { label: '一级', value: '一级' },
      { label: '二级', value: '二级' },
      { label: '三级', value: '三级' },
      { label: '四级', value: '四级' }
    ]
  }
}

// 获取需求状态字典数据
const getDemandStatusOptions = async () => {
  try {
    const res = await portalApi.getDictByCode({ dictType: 'demandStatus' })
    if (res) {
      demandStatusOptions.value = res || []
    } else {
      console.warn('获取需求状态字典数据失败')
    }
  } catch (error) {
    console.error('获取需求状态字典数据失败:', error)
  }
}

const getStatusLabel = (statusValue: string) => {
  const option = demandStatusOptions.value.find((item) => item.value === statusValue)
  return option ? option.label : statusValue
}

const getStatusType: any = (statusValue: string) => {
  if (statusValue === '0') return 'warning' // 未受理
  if (statusValue === '1') return 'success' // 已完成
  return 'default'
}

// 关闭弹窗前确认
const handleCloseDialog = (done: () => void) => {
  done()
}

// 查看需求详情
const handleView = (item: DemandData) => {
  // 填充查看表单数据
  Object.assign(viewForm, {
    id: item.id,
    applicationTitle: item.applicationTitle,
    applicationReason: item.applicationReason,
    applicationScenario: item.applicationScenario,
    useTime: item.useTimeStart && item.useTimeEnd ? [item.useTimeStart, item.useTimeEnd] : [],
    contactPhone: item.contactPhone,
    contactAddress: item.contactAddress,
    serviceScope: item.serviceScope,
    expectedEffect: item.expectedEffect,
    systemName: item.systemName,
    deploymentLocation: item.deploymentLocation,
    systemIp: item.systemIp,
    systemUrl: item.systemUrl,
    levelProtectionCode: item.levelProtectionCode,
    levelProtectionLevel: item.levelProtectionLevel,
    replyContent: item.replyContent || '',
    replyTime: item.replyTime || '',
    status: item.status,
    createTime: item.createTime,
    createId: item.createId,
    replyId: item.replyId
  })

  showViewDialog.value = true
}

// 关闭查看弹窗
const handleCloseViewDialog = (done: () => void) => {
  // 清空查看表单数据
  Object.keys(viewForm).forEach((key) => {
    if (key !== 'useTime') {
      ;(viewForm as any)[key] = ''
    }
  })
  viewForm.useTime = []
  done()
}

// 提交需求
const handleSubmitDemand = async () => {
  if (!demandFormRef.value) return

  try {
    await demandFormRef.value.validate()

    // 准备提交数据
    const submitData = {
      applicationTitle: demandForm.applicationTitle,
      applicationReason: demandForm.applicationReason,
      applicationScenario: demandForm.applicationScenario,
      useTimeStart: demandForm.useTime[0],
      useTimeEnd: demandForm.useTime[1],
      contactPhone: demandForm.contactPhone,
      contactAddress: demandForm.contactAddress,
      serviceScope: demandForm.serviceScope,
      expectedEffect: demandForm.expectedEffect,
      systemName: demandForm.systemName,
      deploymentLocation: demandForm.deploymentLocation,
      systemIp: demandForm.systemIp,
      systemUrl: demandForm.systemUrl,
      levelProtectionCode: demandForm.levelProtectionCode,
      levelProtectionLevel: demandForm.levelProtectionLevel
    }

    // 调用submitInterface接口
    const res = await portalApi.submitInterface(submitData)

    if (res) {
      ElMessage.success('需求提交成功！')
      showSubmitDialog.value = false

      // 重置表单
      demandFormRef.value.resetFields()

      // 重新加载数据
      getMyDemands()
    } else {
      ElMessage.error(res.msg || '需求提交失败')
    }
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

// 打开提交需求弹窗
const handleOpenDemand = () => {
  showSubmitDialog.value = true
}

const getMyDemands = async () => {
  loading.value = true

  tableData.value = []
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await portalApi.getInterfaceListByUser(params)
    if (res) {
      tableData.value = res.list || []
      total.value = res.total || 0
    }
  } catch (error) {
    console.error('获取需求列表失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getMyDemands()
  getLevelProtectionOptions()
  getDemandStatusOptions()
})
</script>

<style scoped lang="scss">
.my-demands-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;

  .search-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    :deep(.el-input__wrapper) {
      width: 450px;
      height: 50px;
    }

    :deep(.el-input-group__append) {
      width: 100px;
      background-color: #ffffff;
      padding: 2px;
    }

    :deep(.el-input-group__append) {
      width: 130px;
    }

    .search-button {
      cursor: pointer;
      margin: 0;
      width: 100%;
      height: 100%;
      padding: 0;
      background-color: #17a7ff;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;

      img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
  }

  .result-sort-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .el-button {
      border: 1px solid #17a7ff;
      color: #17a7ff;
      background-color: transparent;

      &:hover {
        border-color: #17a7ff;
        background-color: #e6f7ff;
        color: #17a7ff;
      }
    }
  }

  .result-count {
    font-size: 14px;
    color: #999999;

    .result-count-number {
      font-size: 18px;
      color: #1faaff;
      margin: 0 8px;
    }
  }

  .demand-cards-container {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .demand-card-item {
    background: #fff url('@/assets/imgs/data/back-data.png') no-repeat center center;
    background-size: cover;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    position: relative;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;

      .card-header-content {
        display: flex;
        align-items: center;

        .card-title {
          font-size: 18px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .card-actions {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #17a7ff !important;
        font-size: 16px;
        cursor: pointer;
      }
    }

    .card-tags {
      margin-bottom: 8px;
    }

    .card-summary {
      display: flex;
      // flex-direction: column;
      gap: 16px;
      margin-bottom: 12px;

      .summary-item {
        display: flex;
        align-items: center;
        gap: 4px;

        .summary-label {
          font-size: 13px;
          color: #909399;
          min-width: 60px;
        }

        .summary-value {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
        }
      }
    }

    .card-footer {
      font-size: 13px;
      color: #909399;
      display: flex;
      gap: 50px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 4px;

        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 12px;

    .page-size-selector {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #606266;
      cursor: pointer;
    }
  }

  /* 查看弹窗样式优化 */
  :deep(.el-form-item.is-disabled .el-form-item__label) {
    color: #606266;
    font-weight: 500;
  }

  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #606266;
  }

  :deep(.el-select.is-disabled .el-input__wrapper) {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
  }
}
</style>
